import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { BlurView } from 'expo-blur';
import { Ionicons } from '@expo/vector-icons';
import { useAuth } from '../contexts/AuthContext';
import { wineAPI } from '../utils/api';
import { theme } from '../styles/theme';

const WinesScreen = ({ navigation }) => {
  const { user } = useAuth();
  const [wines, setWines] = useState([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [filterStatus, setFilterStatus] = useState('stored'); // stored, taken, all

  useEffect(() => {
    fetchWines();
  }, [filterStatus]);

  const fetchWines = async () => {
    setLoading(true);
    try {
      const params = {};
      if (filterStatus !== 'all') {
        params.status = filterStatus;
      }

      const response = await wineAPI.getUserWines(user.id, params);
      if (response.success) {
        setWines(response.data);
      }
    } catch (error) {
      console.error('Fetch wines error:', error);
    } finally {
      setLoading(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await fetchWines();
    setRefreshing(false);
  };

  const renderWine = ({ item }) => (
    <BlurView intensity={15} tint="dark" style={styles.wineCard}>
      <View style={styles.wineHeader}>
        <LinearGradient
          colors={['rgba(212, 175, 55, 0.3)', 'rgba(255, 215, 0, 0.2)']}
          style={styles.wineIcon}
        >
          <Ionicons name="wine" size={32} color={theme.colors.primary} />
        </LinearGradient>
        <View style={styles.wineInfo}>
          <Text style={styles.wineName}>{item.wineName}</Text>
          <Text style={styles.wineType}>{item.wineType}</Text>
        </View>
        <View
          style={[
            styles.statusBadge,
            { backgroundColor: item.status === 'stored' ? theme.colors.success + '30' : theme.colors.textDim + '30' }
          ]}
        >
          <Text
            style={[
              styles.statusText,
              { color: item.status === 'stored' ? theme.colors.success : theme.colors.textDim }
            ]}
          >
            {item.status === 'stored' ? '在库' : '已取'}
          </Text>
        </View>
      </View>

      <View style={styles.wineDetails}>
        <View style={styles.detailRow}>
          <View style={styles.detailItem}>
            <Ionicons name="layers-outline" size={16} color={theme.colors.textSecondary} />
            <Text style={styles.detailLabel}>数量</Text>
            <Text style={styles.detailValue}>
              {item.quantity} {item.unit}
            </Text>
          </View>
          <View style={styles.detailItem}>
            <Ionicons name="calendar-outline" size={16} color={theme.colors.textSecondary} />
            <Text style={styles.detailLabel}>寄存日期</Text>
            <Text style={styles.detailValue}>
              {new Date(item.storageDate).toLocaleDateString('zh-CN')}
            </Text>
          </View>
        </View>

        {item.notes && (
          <View style={styles.notesContainer}>
            <Text style={styles.notesLabel}>备注：</Text>
            <Text style={styles.notesText}>{item.notes}</Text>
          </View>
        )}
      </View>
    </BlurView>
  );

  const renderEmpty = () => (
    <View style={styles.emptyContainer}>
      <Ionicons name="wine-outline" size={64} color={theme.colors.textDim} />
      <Text style={styles.emptyText}>暂无寄存酒记录</Text>
    </View>
  );

  const storedCount = wines.filter(w => w.status === 'stored').length;

  return (
    <LinearGradient colors={['#000000', '#1a1a1a']} style={styles.container}>
      {/* 头部 */}
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Ionicons name="arrow-back" size={24} color={theme.colors.text} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>我的寄存酒</Text>
        <View style={{ width: 24 }} />
      </View>

      {/* 统计卡片 */}
      <BlurView intensity={20} tint="dark" style={styles.statsCard}>
        <LinearGradient
          colors={['rgba(212, 175, 55, 0.1)', 'rgba(255, 215, 0, 0.05)']}
          style={styles.statsGradient}
        >
          <View style={styles.statItem}>
            <Text style={styles.statValue}>{storedCount}</Text>
            <Text style={styles.statLabel}>在库</Text>
          </View>
          <View style={styles.statDivider} />
          <View style={styles.statItem}>
            <Text style={styles.statValue}>{wines.length - storedCount}</Text>
            <Text style={styles.statLabel}>已取出</Text>
          </View>
          <View style={styles.statDivider} />
          <View style={styles.statItem}>
            <Text style={styles.statValue}>{wines.length}</Text>
            <Text style={styles.statLabel}>总数</Text>
          </View>
        </LinearGradient>
      </BlurView>

      {/* 筛选器 */}
      <View style={styles.filterContainer}>
        <TouchableOpacity onPress={() => setFilterStatus('stored')} activeOpacity={0.8}>
          <BlurView
            intensity={filterStatus === 'stored' ? 30 : 15}
            tint="dark"
            style={[styles.filterButton, filterStatus === 'stored' && styles.filterButtonActive]}
          >
            <Text style={[styles.filterText, filterStatus === 'stored' && styles.filterTextActive]}>
              在库
            </Text>
          </BlurView>
        </TouchableOpacity>

        <TouchableOpacity onPress={() => setFilterStatus('taken')} activeOpacity={0.8}>
          <BlurView
            intensity={filterStatus === 'taken' ? 30 : 15}
            tint="dark"
            style={[styles.filterButton, filterStatus === 'taken' && styles.filterButtonActive]}
          >
            <Text style={[styles.filterText, filterStatus === 'taken' && styles.filterTextActive]}>
              已取出
            </Text>
          </BlurView>
        </TouchableOpacity>

        <TouchableOpacity onPress={() => setFilterStatus('all')} activeOpacity={0.8}>
          <BlurView
            intensity={filterStatus === 'all' ? 30 : 15}
            tint="dark"
            style={[styles.filterButton, filterStatus === 'all' && styles.filterButtonActive]}
          >
            <Text style={[styles.filterText, filterStatus === 'all' && styles.filterTextActive]}>
              全部
            </Text>
          </BlurView>
        </TouchableOpacity>
      </View>

      {/* 酒列表 */}
      <FlatList
        data={wines}
        renderItem={renderWine}
        keyExtractor={(item) => item.id.toString()}
        contentContainerStyle={styles.listContent}
        ListEmptyComponent={renderEmpty}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
      />
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: theme.spacing.lg,
    paddingTop: theme.spacing.xxl,
    paddingBottom: theme.spacing.md
  },
  headerTitle: {
    fontSize: theme.fontSizes.xlarge,
    fontWeight: 'bold',
    color: theme.colors.text
  },
  statsCard: {
    marginHorizontal: theme.spacing.lg,
    marginBottom: theme.spacing.md,
    borderRadius: theme.borderRadius.medium,
    overflow: 'hidden',
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  statsGradient: {
    flexDirection: 'row',
    padding: theme.spacing.lg
  },
  statItem: {
    flex: 1,
    alignItems: 'center'
  },
  statValue: {
    fontSize: theme.fontSizes.xxlarge,
    fontWeight: 'bold',
    color: theme.colors.primary,
    marginBottom: theme.spacing.xs
  },
  statLabel: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textSecondary
  },
  statDivider: {
    width: 1,
    backgroundColor: theme.colors.divider,
    marginHorizontal: theme.spacing.md
  },
  filterContainer: {
    flexDirection: 'row',
    gap: theme.spacing.sm,
    paddingHorizontal: theme.spacing.lg,
    marginBottom: theme.spacing.md
  },
  filterButton: {
    paddingHorizontal: theme.spacing.lg,
    paddingVertical: theme.spacing.sm,
    borderRadius: theme.borderRadius.round,
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  filterButtonActive: {
    borderColor: theme.colors.primary
  },
  filterText: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.textSecondary
  },
  filterTextActive: {
    color: theme.colors.primary,
    fontWeight: 'bold'
  },
  listContent: {
    padding: theme.spacing.lg,
    paddingTop: 0
  },
  wineCard: {
    borderRadius: theme.borderRadius.medium,
    padding: theme.spacing.md,
    marginBottom: theme.spacing.md,
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  wineHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: theme.spacing.md
  },
  wineIcon: {
    width: 56,
    height: 56,
    borderRadius: theme.borderRadius.medium,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: theme.spacing.md
  },
  wineInfo: {
    flex: 1
  },
  wineName: {
    fontSize: theme.fontSizes.large,
    color: theme.colors.text,
    fontWeight: 'bold',
    marginBottom: 4
  },
  wineType: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.textSecondary
  },
  statusBadge: {
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.xs,
    borderRadius: theme.borderRadius.round
  },
  statusText: {
    fontSize: theme.fontSizes.small,
    fontWeight: '600'
  },
  wineDetails: {
    borderTopWidth: 1,
    borderTopColor: theme.colors.divider,
    paddingTop: theme.spacing.md
  },
  detailRow: {
    flexDirection: 'row',
    gap: theme.spacing.lg
  },
  detailItem: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    gap: theme.spacing.xs
  },
  detailLabel: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textSecondary
  },
  detailValue: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.text,
    fontWeight: '600'
  },
  notesContainer: {
    flexDirection: 'row',
    marginTop: theme.spacing.sm,
    paddingTop: theme.spacing.sm,
    borderTopWidth: 1,
    borderTopColor: theme.colors.divider
  },
  notesLabel: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textDim,
    marginRight: theme.spacing.xs
  },
  notesText: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textSecondary,
    flex: 1
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: theme.spacing.xxl * 2
  },
  emptyText: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.textDim,
    marginTop: theme.spacing.md
  }
});

export default WinesScreen;
